import 'dart:convert';

import 'package:concierge/app/widgets/ms_app_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:url_launcher/url_launcher.dart';

import '../../../generated/locales.g.dart';
import '../../widgets/modal.dart';

class EnhancedWebView extends StatefulWidget {
  const EnhancedWebView({super.key});

  @override
  State<EnhancedWebView> createState() => _EnhancedWebViewState();
}

class _EnhancedWebViewState extends State<EnhancedWebView> {
  final GlobalKey webViewKey = GlobalKey();
  InAppWebViewController? webViewController;
  WebResourceError? error;
  String url = '';
  String title = '';
  double progress = 0;
  bool canGoBack = false;
  bool canGoForward = false;
  final TextEditingController urlController = TextEditingController();

  // JavaScript通道名称
  static const String jsChannelName = 'FlutterJSChannel';

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    setState(() {
      url = args['url'] ?? 'https://www.google.com';
      title = args['title'] ?? '浏览器';
    });
    urlController.text = url;
  }

  @override
  void dispose() {
    urlController.dispose();
    super.dispose();
  }

  // 加载URL
  void loadUrl(String url) {
    if (webViewController != null) {
      if (!url.startsWith('http')) {
        url = 'https://$url';
      }
      webViewController!.loadUrl(urlRequest: URLRequest(url: WebUri(url)));
      urlController.text = url;
    }
  }

  // 刷新页面
  void reload() {
    if (webViewController != null) {
      webViewController!.reload();
    }
  }

  // 前进
  void goForward() {
    if (webViewController != null && canGoForward) {
      webViewController!.goForward();
    }
  }

  // 后退
  void goBack() {
    if (webViewController != null && canGoBack) {
      webViewController!.goBack();
    }
  }

  // 将Dart值转换为JavaScript值
  String _convertToJsValue(dynamic value) {
    if (value is String) {
      return '"${value.replaceAll('"', '\\"')}"';
    } else if (value is num) {
      return value.toString();
    } else if (value is bool) {
      return value.toString();
    } else if (value is List) {
      return '[${value.map((e) => _convertToJsValue(e)).join(',')}]';
    } else if (value is Map) {
      final entries = value.entries
          .map(
            (e) => '${_convertToJsValue(e.key)}:${_convertToJsValue(e.value)}',
          )
          .join(',');
      return '{$entries}';
    }
    return 'null';
  }

  //--------------------------------todo---------------------------------------

  // todo  从Flutter调用JavaScript方法
  Future<void> callJavaScript(String script) async {
    if (webViewController != null) {
      try {
        await webViewController!.evaluateJavascript(source: script);
      } catch (e) {
        // logger.e('JavaScript执行错误: $e');
      }
    }
  }

  // 调用网页中注册的JavaScript方法（带参数）
  Future<dynamic> callJavaScriptMethod(
    String methodName, [
    dynamic parameters,
  ]) async {
    if (webViewController != null) {
      try {
        final script = parameters != null
            ? 'window.$jsChannelName.callJavaScriptMethod("$methodName", ${_convertToJsValue(parameters)})'
            : 'window.$jsChannelName.callJavaScriptMethod("$methodName")';
        final result = await webViewController!.evaluateJavascript(
          source: script,
        );
        return result;
      } catch (e) {
        // logger.e('调用JavaScript方法错误: $e');
        return null;
      }
    }
    return null;
  }

  //------------------------------todo------------------------------------------
  // todo 注册本地方法供JavaScript调用（带参数）
  void _registerNativeMethods(InAppWebViewController controller) {
    controller.addJavaScriptHandler(
      handlerName: 'showToast',
      callback: (args) {
        final message = args.isNotEmpty ? args[0] : '默认消息';
        Modal.toast(title: 'Toast: $message');
        return {'success': true, 'message': 'Toast显示成功'};
      },
    );

    // 示例方法：获取设备信息
    controller.addJavaScriptHandler(
      handlerName: 'getDeviceInfo',
      callback: (args) {
        return {
          'platform': 'Android/iOS',
          'version': '2.0.0',
          'screenWidth': MediaQuery.of(context).size.width,
          'screenHeight': MediaQuery.of(context).size.height,
        };
      },
    );

    // 示例方法：处理用户数据（带复杂参数）
    controller.addJavaScriptHandler(
      handlerName: 'saveUserData',
      callback: (args) {
        if (args.isNotEmpty && args[0] is Map) {
          final userData = args[0];
          //logger.i('保存用户数据: $userData');
          // 这里可以实际保存到本地存储
          return {
            'success': true,
            'data': userData,
            'timestamp': DateTime.now().toIso8601String(),
          };
        }
        return {'success': false, 'error': '无效的用户数据'};
      },
    );

    // 示例方法：计算数学运算
    controller.addJavaScriptHandler(
      handlerName: 'calculate',
      callback: (args) {
        if (args.length >= 2) {
          final num1 = double.tryParse(args[0].toString()) ?? 0;
          final num2 = double.tryParse(args[1].toString()) ?? 0;
          final String operation = args.length >= 3
              ? args[2].toString()
              : 'add';

          double result;
          switch (operation) {
            case 'add':
              result = num1 + num2;
              break;
            case 'subtract':
              result = num1 - num2;
              break;
            case 'multiply':
              result = num1 * num2;
              break;
            case 'divide':
              result = num2 != 0 ? num1 / num2 : double.infinity;
              break;
            default:
              result = num1 + num2;
          }

          return {
            'result': result,
            'operation': operation,
            'expression': '$num1 ${_getOperationSymbol(operation)} $num2',
          };
        }
        return {'error': '参数不足'};
      },
    );
  }

  // 获取运算符号
  String _getOperationSymbol(String operation) {
    switch (operation) {
      case 'add':
        return '+';
      case 'subtract':
        return '-';
      case 'multiply':
        return '*';
      case 'divide':
        return '/';
      default:
        return '+';
    }
  }

  // 调用JavaScript方法
  void _callJavaScriptMethod() {
    if (webViewController != null) {
      // 直接调用预设的JavaScript方法
      callJavaScriptMethod('showAlert', 'Hello from hjc ! 你好，hjc !')
          .then((result) {
            //logger.i('JavaScript方法调用结果: $result');
            Get.snackbar(LocaleKeys.prompt.tr, "调用成功");
          })
          .catchError((error) {
            // logger.e('调用JavaScript方法错误: $error');
            Get.snackbar(LocaleKeys.prompt.tr, '调用失败: $error');
          });
    } else {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('WebView未初始化')));
    }
  }

  Future<void> autoUser() async {
    // todo  Google登录测试--------------------------------
    // 1. 构造谷歌授权URL（替换为你的GCP客户端ID）
    const String clientId =
        '25516843599-t6uap71plbunlegfc27uk83d0n8kaent.apps.googleusercontent.com'; // 从GCP控制台获取
    const String redirectUri =
        'https://life-api.vertu.cn/test/v3/auth/google'; // 与原生配置一致
    const String scope = 'openid email profile'; // 请求的用户信息范围

    final String authUrl = Uri.encodeFull(
      'https://accounts.google.com/o/oauth2/v2/auth'
      '?client_id=$clientId'
      '&redirect_uri=$redirectUri'
      '&response_type=code' // 必须为code，获取授权码
      '&scope=$scope'
      '&access_type=offline', // 可选，需要刷新令牌时添加
    );
    // 2. 使用外部浏览器打开授权页面
    if (await canLaunchUrl(Uri.parse(authUrl))) {
      await launchUrl(Uri.parse(authUrl), mode: LaunchMode.externalApplication);
    }
  }

  Future<void> signIn() async {
    const String _backendAuthEndpoint =
        'https://your-domain.com/api/auth/google'; // 你的PHP后端接收code的API

    const String clientId =
        '25516843599-t6uap71plbunlegfc27uk83d0n8kaent.apps.googleusercontent.com'; // 从GCP控制台获取
    const String redirectUri =
        'https://life-api.vertu.cn/test/v3/auth/google'; // 与原生配置一致

    const String scope = 'openid email profile'; // 请求的用户信息范围

    // 构建认证请求URL
    final String authUrl =
        'https://accounts.google.com/o/oauth2/v2/auth?'
        'response_type=code&'
        'client_id=$clientId&'
        'redirect_uri=${Uri.encodeComponent(redirectUri)}&'
        'scope=openid%20email%20profile&' // 请求访问邮箱和基本资料
        'state=random_string_123'; // 可选，用于防止CSRF攻击

    try {
      // 3. 跳转到浏览器进行登录授权
      final result = await FlutterWebAuth2.authenticate(
        url: authUrl,
        callbackUrlScheme: Uri.parse(redirectUri).scheme,
      );

      // 4. 从重定向回来的URL中解析出授权码 `code`
      final Uri returnedUri = Uri.parse(result);
      final String? authorizationCode = returnedUri.queryParameters['code'];

      if (authorizationCode == null) {
        throw Exception('Authorization code not found');
      }
      print("authorizationCode:$authorizationCode");

      // 5. 将授权码发送给自己的后端
      final http.Response response = await http.post(
        Uri.parse(_backendAuthEndpoint),
        body: json.encode({'code': authorizationCode}),
        headers: {'Content-Type': 'application/json'},
      );

      // 6. 处理后端返回的token和用户信息
      if (response.statusCode == 200) {
        final Map<String, dynamic> responseData = json.decode(response.body);
        final String jwtToken = responseData['token'];
        final userData = responseData['user'];

        // 保存JWT token到本地存储（如shared_preferences），用于后续API请求
        print('Login Success! JWT: $jwtToken, User: $userData');
      } else {
        // 处理错误
        print('Backend error: ${response.body}');
      }
    } catch (e) {
      print('Sign in failed: $e');
    }
  }

  //--------------------------------todo---------------------------------------
  // 构建地址栏
  Widget _buildAddressBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
      ),
      child: Row(
        children: [
          // 返回按钮
          IconButton(
            icon: Icon(Icons.arrow_back, size: 20.w),
            onPressed: goBack,
            color: canGoBack ? Colors.blue : Colors.grey,
          ),
          // 前进按钮
          IconButton(
            icon: Icon(Icons.arrow_forward, size: 20.w),
            onPressed: goForward,
            color: canGoForward ? Colors.blue : Colors.grey,
          ),
          // 刷新按钮
          IconButton(
            icon: Icon(Icons.refresh, size: 20.w),
            onPressed: reload,
            color: Colors.blue,
          ),
          // 地址输入框
          Expanded(
            child: Container(
              height: 36.h,
              margin: EdgeInsets.symmetric(horizontal: 8.w),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(18.w),
                border: Border.all(color: Colors.grey[300]!),
              ),
              child: TextField(
                controller: urlController,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 12.w,
                    vertical: 8.h,
                  ),
                  border: InputBorder.none,
                  hintText: '输入网址',
                  suffixIcon: IconButton(
                    icon: Icon(Icons.search, size: 18.w),
                    onPressed: () => loadUrl(urlController.text),
                  ),
                ),
                onSubmitted: (value) => loadUrl(value),
                style: TextStyle(fontSize: 14.sp),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MSAppBar(
        title: title,
        backgroundColor: context.theme.colorScheme.onPrimaryContainer,
      ),
      body: Column(
        children: [
          // _buildAddressBar(),
          Expanded(
            child: Stack(
              children: [
                InAppWebView(
                  key: webViewKey,
                  initialSettings: InAppWebViewSettings(
                    transparentBackground: true,
                    javaScriptEnabled: true,
                    javaScriptCanOpenWindowsAutomatically: true,
                    mediaPlaybackRequiresUserGesture: false,
                  ),
                  initialUrlRequest: URLRequest(url: WebUri(url)),
                  onWebViewCreated: (controller) {
                    webViewController = controller;
                    // 注册JavaScript处理器
                    controller.addJavaScriptHandler(
                      handlerName: 'handleMessageFromFlutter',
                      callback: (args) {
                        // 处理来自JavaScript的消息
                        //logger.i('收到来自JavaScript的消息: $args');
                        // 这里可以处理具体的消息逻辑
                        return {'status': 'success', 'message': '消息已收到'};
                      },
                    );

                    // 注册所有本地方法供JavaScript调用
                    _registerNativeMethods(controller);
                  },
                  onPermissionRequest: (controller, request) async {
                    return PermissionResponse(
                      resources: request.resources,
                      action: PermissionResponseAction.GRANT,
                    );
                  },
                  shouldOverrideUrlLoading:
                      (controller, navigationAction) async {
                        final uri = navigationAction.request.url!;
                        if (![
                          "http",
                          "https",
                          "file",
                          "chrome",
                          "data",
                          "javascript",
                          "about",
                        ].contains(uri.scheme)) {
                          await launchUrl(uri);
                          return NavigationActionPolicy.CANCEL;
                        }
                        return NavigationActionPolicy.ALLOW;
                      },
                  onReceivedError: (controller, request, err) {
                    setState(() {
                      error = err;
                    });
                  },
                  onProgressChanged: (controller, progress) {
                    setState(() {
                      this.progress = progress / 100;
                    });
                  },
                  onLoadStop: (controller, url) async {
                    setState(() {
                      this.url = url?.toString() ?? '';
                      urlController.text = this.url;
                    });
                    // 检查导航状态
                    final canBack = await controller.canGoBack();
                    final canForward = await controller.canGoForward();
                    setState(() {
                      canGoBack = canBack;
                      canGoForward = canForward;
                    });
                    // 注入JavaScript通信桥
                    await controller.evaluateJavascript(
                      source:
                          '''
                      // 创建Flutter通信对象
                      window.$jsChannelName = {
                        // 调用Flutter方法
                        callFlutter: function(message) {
                          window.flutter_inappwebview.callHandler('handleMessageFromFlutter', message);
                        },
                        
                        // 注册JavaScript方法供Flutter调用
                        methods: {},
                        
                        // 注册JavaScript方法
                        registerMethod: function(methodName, callback) {
                          this.methods[methodName] = callback;
                        },
                        
                        // 调用JavaScript方法
                        callJavaScriptMethod: function(methodName, parameters) {
                          if (this.methods[methodName]) {
                            return this.methods[methodName](parameters);
                          }
                          return null;
                        }
                      };
                      
                      // 示例：注册一个测试方法
                      window.$jsChannelName.registerMethod('showAlert', function(message) {
                        alert('来自Flutter的消息: ' + message);
                        return 'Alert shown';
                      });
                      
                      console.log('Flutter-Javascript通信桥已初始化');
                    ''',
                    );
                  },
                  onUpdateVisitedHistory: (controller, url, isReload) async {
                    setState(() {
                      this.url = url?.toString() ?? '';
                      urlController.text = this.url;
                    });
                    // 检查导航状态
                    if (webViewController != null) {
                      final canBack = await webViewController!.canGoBack();
                      final canForward = await webViewController!
                          .canGoForward();
                      setState(() {
                        canGoBack = canBack;
                        canGoForward = canForward;
                      });
                    }
                  },
                ),
                // if (error != null)
                //   Padding(
                //     padding: EdgeInsets.symmetric(horizontal: 24.w),
                //     child: Column(
                //       mainAxisAlignment: MainAxisAlignment.center,
                //       children: [
                //         Text(
                //           '加载失败',
                //           style: TextStyle(
                //               fontSize: 16.sp, fontWeight: FontWeight.bold),
                //           textAlign: TextAlign.center,
                //         ),
                //         SizedBox(height: 8.h),
                //         Text(
                //           '无法加载网页: $url',
                //           style: TextStyle(fontSize: 14.sp, color: Colors.grey),
                //           textAlign: TextAlign.center,
                //         ),
                //         SizedBox(height: 16.h),
                //         ElevatedButton(
                //           onPressed: reload,
                //           child: Text('重新加载'),
                //         ),
                //       ],
                //     ),
                //   ),
                if (error == null && progress < 1.0)
                  LinearProgressIndicator(
                    value: progress,
                    color: Colors.blue,
                    backgroundColor: Colors.transparent,
                  ),
              ],
            ),
          ),
        ],
      ),
      // 底部操作栏
      bottomNavigationBar: BottomAppBar(
        height: 50.h,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            IconButton(
              icon: Icon(Icons.home, size: 24.w),
              onPressed: () => loadUrl('https://www.google.com'),
              tooltip: '主页',
            ),
            IconButton(
              icon: Icon(Icons.share, size: 24.w),
              onPressed: () {
                // 分享功能
                //logger.i('分享网页: $url');
              },
              tooltip: '分享',
            ),
            IconButton(
              icon: Icon(Icons.more_vert, size: 24.w),
              onPressed: () {
                // 更多选项
                showModalBottomSheet(
                  context: context,
                  backgroundColor: context.theme.colorScheme.onPrimaryContainer,
                  builder: (context) => Container(
                    padding: EdgeInsets.all(16.w),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        ListTile(
                          leading: Icon(Icons.info),
                          title: Text('网页信息'),
                          onTap: () {
                            Navigator.pop(context);
                            showDialog(
                              context: context,
                              builder: (context) => AlertDialog(
                                title: Text('网页信息'),
                                content: Text('URL: $url\n标题: $title'),
                                actions: [
                                  TextButton(
                                    onPressed: () => Navigator.pop(context),
                                    child: Text('关闭'),
                                  ),
                                ],
                              ),
                            );
                          },
                        ),
                        ListTile(
                          leading: Icon(Icons.code),
                          title: Text('测试调用JavaScript调用'),
                          onTap: () {
                            Navigator.pop(context);
                            callJavaScript('''
                              if (window.$jsChannelName) {
                                window.$jsChannelName.callFlutter('测试消息来自JavaScript');
                                alert('JavaScript调用Flutter成功！');
                              }
                            ''');
                          },
                        ),
                        ListTile(
                          leading: Icon(Icons.phone_android),
                          title: Text('测试调用本地方法'),
                          onTap: () {
                            Navigator.pop(context);
                            // 演示调用JavaScript方法
                            callJavaScriptMethod(
                              'showAlert',
                              'Flutter调用JavaScript成功！',
                            ).then((result) {
                              //logger.i('JavaScript方法调用结果: $result');
                            });
                          },
                        ),
                        ListTile(
                          leading: Icon(Icons.phone_android),
                          title: Text('Google登录测试'),
                          onTap: () async {
                            // autoUser();
                            signIn();
                          },
                        ),
                        ListTile(
                          leading: Icon(Icons.javascript, size: 24.w),
                          onTap: () {
                            // 调用JavaScript方法
                            _callJavaScriptMethod();
                          },
                          title: Text("调用JavaScript"),
                        ),
                      ],
                    ),
                  ),
                );
              },
              tooltip: '更多',
            ),
          ],
        ),
      ),
    );
  }
}
